/*
  学习目标：实现发表评论
  步骤：
     1. 受控组件改造
      1.1 state控制value
      1.2 onChange配合setState, 修改数据
     2. 新增评论
      2.1 定义新增事件
      2.2 绑定新增事件
      2.3 通过setState添加新数据到list中
*/

import React from 'react';

import './index.css';

export default class App extends React.Component {
  state = {
    username: '',
    content: '',

    list: [
      { username: '张三', content: '狂1', id: 1 },
      { username: '李四', content: '狂徒2', id: 2 },
      { username: '王五', content: '狂徒3', id: 3 },
    ],
  };

  handleDelById = (id) => {
    const { list } = this.state;
    const newList = list.filter((item) => item.id !== id);

    this.setState({ list: newList });
  };

  handleClear = () => {
    this.setState({ list: [] });
  };
  handleChange = (e) => {
    const { name, value } = e.target;
    this.setState({ [name]: value });
  };

  // 2.1 定义新增事件
  handleAdd = (e) => {
    e.preventDefault();
    // 2.3 通过setState添加新数据到list中
    const { list, username, content } = this.state;
    const newList = [{ username, content, id: Date.now() }, ...list];
    this.setState({ list: newList, username: '', content: '' });
  };

  render() {
    const { list, username, content } = this.state;
    return (
      <div className="app">
        <form>
          <input
            // 1.1 state控制value
            name="username"
            value={username}
            // 1.2 onChange配合setState, 修改数据
            onChange={this.handleChange}
            className="user"
            type="text"
            placeholder="请输入评论人"
          />
          <br />
          <textarea
            name="content"
            value={content}
            onChange={this.handleChange}
            className="content"
            cols="30"
            rows="10"
            placeholder="请输入评论内容"
          />
          <br />
          <button
            // 2.2 绑定新增事件
            onClick={this.handleAdd}
          >
            发表评论
          </button>
          <button type="button" onClick={this.handleClear}>
            清空评论
          </button>
        </form>
        {list.length ? (
          <ul>
            {list.map((item) => (
              <li key={item.id}>
                <h3>评论人: {item.username}</h3>
                <p>评论内容：{item.content}</p>
                <button onClick={() => this.handleDelById(item.id)}>删除</button>
              </li>
            ))}
          </ul>
        ) : (
          <div>暂无数据</div>
        )}
      </div>
    );
  }
}
